package service

import (
	"gitee.com/sdumeeting/sfu-server/pkg/response"
	"net/http"
	"strconv"
)

type StartScreenSharingHandler struct{}

// 启动屏幕共享
// 需要参数：会议 id，用户 id
// 用户 id 用于判断该用户是否在该会议里面
func (h *StartScreenSharingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var userId, meetingId int
	var err error

	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization")

	// 用户 id
	userId, err = strconv.Atoi(r.PostFormValue("userId"))
	if err != nil {
		_, _ = w.Write(response.ParamErr.ToByte())
		return
	}

	// 会议号
	meetingId, err = strconv.Atoi(r.PostFormValue("meetingId"))
	if err != nil {
		_, _ = w.Write(response.ParamErr.ToByte())
		return
	}

	// 获取会议
	meeting := meetingList.GetMeetingById(meetingId)
	if meeting == nil {
		_, _ = w.Write(response.MeetingNotExist.ToByte())
		return
	}

	// 判断该用户是否在会议中
	if meeting.GetUsers()[userId] == nil {
		_, _ = w.Write(response.UserNotInMeeting.ToByte())
		return
	}

	// 启动屏幕共享
	err = meeting.StartScreenSharing()
	if err != nil {
		_, _ = w.Write(response.ScreenSharingOn.ToByte())
		return
	}

	// 返回成功信息
	_, _ = w.Write(response.Success.ToByte())
}

type EndScreenSharingHandler struct{}

// 关闭屏幕共享
// 需要参数：会议 id，用户 id
// 用户 id 用于判断该用户是否在该会议里面
func (h *EndScreenSharingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var userId, meetingId int
	var err error

	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization")

	// 用户 id
	userId, err = strconv.Atoi(r.PostFormValue("userId"))
	if err != nil {
		_, _ = w.Write(response.ParamErr.ToByte())
		return
	}

	// 会议号
	meetingId, err = strconv.Atoi(r.PostFormValue("meetingId"))
	if err != nil {
		_, _ = w.Write(response.ParamErr.ToByte())
		return
	}

	// 获取会议
	meeting := meetingList.GetMeetingById(meetingId)
	if meeting == nil {
		_, _ = w.Write(response.MeetingNotExist.ToByte())
		return
	}

	// 判断该用户是否在会议中
	if meeting.GetUsers()[userId] == nil {
		_, _ = w.Write(response.UserNotInMeeting.ToByte())
		return
	}

	// 关闭屏幕共享
	err = meeting.EndScreenSharing()
	if err != nil {
		_, _ = w.Write(response.ScreenSharingOff.ToByte())
		return
	}

	// 返回成功信息
	_, _ = w.Write(response.Success.ToByte())
}
